
package com.zcp.notepad;

import com.zcp.notepad.NotePad.Notes;
import com.zcp.notepad.NotePad.Settings;
import com.zcp.notepad.NotePad.WidgetInfo;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputFilter.LengthFilter;
import android.text.TextUtils;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;

public class NoteEditorActivity extends Activity {

    private static final String[] PROJECTION = new String[] {
            Notes._ID, // 0
            Notes.NOTE, // 1
            Notes.TITLE, // 2
            Notes.COLOR, // 3
            Notes.MODIFIED_DATE,// 4
            Notes.TYPE, // 5
            Notes.LOCK,// 6
            Notes.REMIND,// 7
            Notes.REMIND_TIME, // 8
    };

    /** The index of the note column */
    private static final int COLUMN_INDEX_NOTE = 1;

    /** The index of the title column */
    private static final int COLUMN_INDEX_TITLE = 2;

    /** The index of the color column */
    private static final int COLUMN_INDEX_COLOR = 3;

    /** The index of the modified column */
    private static final int COLUMN_INDEX_MODIFIED = 4;

    /** The index of the type column */
    private static final int COLUMN_INDEX_TYPE = 5;

    private static final int COLUMN_INDEX_LOCK = 6;

    private static final int COLUMN_INDEX_REMIND = 7;

    private static final int COLUMN_INDEX_REMIND_TIME = 8;

    // This is our state data that is stored when freezing.
    private static final String ORIGINAL_CONTENT = "origContent";

    // The different distinct states the activity can be run in.
    private static final int STATE_EDIT = 0;

    private static final int STATE_INSERT = 1;

    private static final String TAG = "NoteEditorActivity";

    private int mState;

    private Uri mUri;

    private Cursor mCursor;

    // 文本编辑栏
    private MyLinkEditText mContentView;

    // 标题
    private TextView mTitleView;

    // 顶部栏
    private View topBar;

    // 完成按钮
    private Button btnDone;

    // 取消按钮
    private Button btnCancel;

    private String mOriginalContent;

    private String mColor;

    private String origColor;

    private String mTitle;

    private String oldDateTitle;

    private String setRemind;

    // private String expireRemind;

    private int mType;

    // 原类型
    private int origType;

    private String noteContent;

    private LinkedList<ChecklistEditText> checklistItems;

    private LinearLayout mChecklistLayout;

    private boolean isTypeChanged;

    private boolean isWidgetRequest;// 请求是否来自widget

    private boolean isShortcutRequest;// 请求是否来自shortcut

    private boolean isListRequest;// 请求是否来自列表，用于判断是否弹出密码框，判断完后即置为false

    private boolean isFromAlarm;// 请求是否来自定时提醒

    private int mWidgetId;

    private int mWidgetSize;

    private ImageView lockImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.note_editor);
        final Intent intent = getIntent();

        final String action = intent.getAction();
        mUri = intent.getData();
        if (Intent.ACTION_EDIT.equals(action)) {
            mState = STATE_EDIT;
            mCursor = managedQuery(mUri, PROJECTION, null, null, null);
            mWidgetId = intent.getIntExtra("widget_id", -1);
            mWidgetSize = intent.getIntExtra("widget_size", -1);

        } else if (Intent.ACTION_INSERT.equals(action)) {

            mState = STATE_INSERT;

            if (mUri == null) {
                mUri = Notes.CONTENT_URI;
            }
            mWidgetId = intent.getIntExtra("widget_id", -1);
            mWidgetSize = intent.getIntExtra("widget_size", -1);
        } else {
            // unknown action!
            Log.e(TAG, "Unknown action, exiting");
            finish();
            return;
        }

        isWidgetRequest = mWidgetId != -1 ? true : false;
        isShortcutRequest = intent.getBooleanExtra("isShortcut", false);
        isListRequest = intent.getBooleanExtra("isListRequest", false);
        isFromAlarm = intent.getBooleanExtra("isFromAlarm", false);
        topBar = this.findViewById(R.id.topBar);
        mContentView = (MyLinkEditText) this.findViewById(R.id.note);
        mContentView.setActivity(this);
        mContentView.setAutoLinkMask(Linkify.ALL);
        mContentView.setLinksClickable(false);
        lockImage = (ImageView) this.findViewById(R.id.lockImage);
        mTitleView = (TextView) this.findViewById(R.id.noteTitle);
        mChecklistLayout = (LinearLayout) this.findViewById(R.id.checklistLayout);
        mType = -1;
        // If an instance of this activity had previously stopped, we can
        // get the original text it started with.
        if (savedInstanceState != null) {
            mOriginalContent = savedInstanceState.getString(ORIGINAL_CONTENT);
        }

        checklistItems = new LinkedList<ChecklistEditText>();
        btnDone = (Button) this.findViewById(R.id.noteDone);
        btnCancel = (Button) this.findViewById(R.id.noteCancel);

        btnDone.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                boolean success = true;
                if (isChanged()) {
                    success = saveNote();
                }
                if (success) {
                    Intent i = new Intent(NoteEditorActivity.this, NoteListActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    if (isWidgetRequest) {
                        i.putExtra("isExit", true);
                    }
                    startActivity(i);

                    finish();
                }
            }
        });

        btnCancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();

            }
        });

        ((Button) this.findViewById(R.id.btnColor)).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showColorSelector();
            }
        });

        setRemind = getString(R.string.have_set_remind);
        // expireRemind = getString(R.string.remind_has_expired);
    }

    /**
     * 获取noteid,若为新增的note返回-1
     * 
     * @return
     */
    private int getNoteId() {
        if (mState == STATE_EDIT) {
            return Integer.parseInt(mUri.getPathSegments().get(1));
        } else {
            return -1;
        }
    }

    private AlertDialog myDialog;

    @Override
    protected void onResume() {
        super.onResume();
        int noteId = getNoteId();

        if (noteId != -1 && Util.isLock(this, noteId)) {
            if (isListRequest) {
                initNote();
                isListRequest = false;
                return;
            }
            // 在输入密码以后，不点击确定，这时候有电话等类似并发操作，操作完以后，密码框还会存在。
            if (myDialog == null) {
                myDialog = Util.getUnlockDialog(this, getNoteId(), new unlockCallBack());
                myDialog.show();
            }
        } else {
            initNote();
        }

    }

    @Override
    protected void onDestroy() {
        myDialog = null;
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        mOriginalContent = getNoteContent();
        super.onPause();
    }

    private void initNote() {

        if (mCursor != null && mCursor.moveToFirst()) {

            long modified = mCursor.getLong(COLUMN_INDEX_MODIFIED);
            String date = Util.getDateStr(this, modified) + " " + Util.getTimeStr(this, modified);
            oldDateTitle = date;
            String note = mCursor.getString(COLUMN_INDEX_NOTE);
            noteContent = note;
            mColor = mCursor.getString(COLUMN_INDEX_COLOR);
            int remind = mCursor.getInt(COLUMN_INDEX_REMIND);
            String remindTime = mCursor.getString(COLUMN_INDEX_REMIND_TIME);
            // 设置是否已经定时提醒
            if (NotePad.DataValue.IS_REMIND == remind) {
                long setTime = Long.valueOf(remindTime);
                date = setRemindDate(setTime, date);
            }
            if (mType == -1) {
                mType = mCursor.getInt(COLUMN_INDEX_TYPE);
                origType = mType;
            }

            mTitle = mCursor.getString(COLUMN_INDEX_TITLE);
            if (mOriginalContent != null) {
                note = mOriginalContent;
            }
            mContentView.setText(note);
            mTitleView.setText(date);
            if (mOriginalContent == null) {
                mOriginalContent = note;
            }

            switchColor(mColor);
            if (mCursor.getInt(COLUMN_INDEX_LOCK) == 1) {
                lockImage.setVisibility(View.VISIBLE);
            } else {
                lockImage.setVisibility(View.GONE);
            }

            // // 如果是定时提醒中打开，那么就设置数据中提醒为无
            // if (isFromAlarm) {
            // int id = getNoteId();
            // if (id != -1) {
            // Util.setNoteDataBaseHaveAlarm(this, Long.valueOf(id),
            // NotePad.DataValue.IS_UNREMIND, 0);
            // }
            // }

        } else {
            // 有Id确没有数据，说明已经被删除
            if (getNoteId() != -1 && isShortcutRequest) {
                Toast.makeText(this, this.getString(R.string.have_delete), Toast.LENGTH_LONG)
                        .show();
            }
            noteContent = "";
            mColor = Notes.Color.ORANGE;
            oldDateTitle = Util.getDateStr(this, System.currentTimeMillis()) + " "
                    + Util.getTimeStr(this, System.currentTimeMillis());
            mTitleView.setText(oldDateTitle);
            if (mType == -1) {
                mType = Notes.TYPE_TEXT;
            }
        }
        origColor = mColor;
        setNoteContent(mType);
    }

    /**
     * 设置定时提醒时间
     * 
     * @param remindTime 定时提醒时间。
     * @param date 本记事的格式化后修改时间。
     */
    public String setRemindDate(long remindTime, String date) {

        if (System.currentTimeMillis() > remindTime) {
            int id = getNoteId();
            if (id != -1) {
                Util.setNoteDataBaseHaveAlarm(this, Long.valueOf(id),
                        NotePad.DataValue.IS_UNREMIND, 0);
            }
        } else {

            date = getShowRemind(remindTime, date);
        }

        return date;
    }

    /**
     * 获取时间格式
     * 
     * @param remindTime
     * @param date
     * @return
     */
    private String getShowRemind(long remindTime, String date) {
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        if (df1.format(new Date(System.currentTimeMillis())).equals(
                df1.format(new Date(remindTime)))) {
            // 如果是同一天，提醒只是显示hh:mm 否则显示日期
            date = date + " " + setRemind + Util.getTimeStr(this, remindTime);
        } else {
            date = date + " " + setRemind + Util.getDateStr(this, remindTime) + " "
                    + Util.getTimeStr(this, remindTime);
        }
        return date;
    }

    /**
     * 刷新提醒时间显示。
     * 
     * @param remindTime
     */
    public void refreshTitle(long remindTime) {
        if (0 == remindTime) {
            mTitleView.setText(oldDateTitle);
            return;
        }

        if (System.currentTimeMillis() < remindTime) {
            String show = oldDateTitle;
            show = getShowRemind(remindTime, show);
            mTitleView.setText(show);

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuItem newNoteItem = menu.add(0, 1, 1, R.string.newNote).setIcon(R.drawable.new_note);
        MenuItem shareItem = menu.add(0, 2, 2, R.string.Share).setIcon(R.drawable.share);
        MenuItem homeItem = menu.add(0, 3, 3, R.string.Add_to_homeswcreen).setIcon(
                R.drawable.add_to_homescreen);
        MenuItem deleteItem = menu.add(1, 4, 4, R.string.Delete).setIcon(R.drawable.delete);
        menu.add(1, 5, 5, R.string.checklist).setIcon(R.drawable.checklist);
        MenuItem lockItem = menu.add(1, 6, 6, R.string.lock).setIcon(R.drawable.lock);
        MenuItem remindItem = menu.add(1, 7, 7, R.string.remind).setIcon(R.drawable.alert_icon);
        // menu.add(1, 8, 8, R.string.unremind).setIcon(R.drawable.alert_icon2);
        // 新建便签的时候指定的菜单不可用
        if (mState == STATE_INSERT) {
            newNoteItem.setEnabled(false);
            shareItem.setEnabled(false);
            homeItem.setEnabled(false);
            deleteItem.setEnabled(false);
            lockItem.setEnabled(false);
            remindItem.setEnabled(false);
        }
        return true;
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (menu == null) {
            return false;
        }
        MenuItem checklistItem = menu.getItem(4);
        MenuItem lockItem = menu.getItem(5);
        MenuItem remindItem = menu.getItem(6);
        if (mType == Notes.TYPE_CHECKLIST) {
            checklistItem.setTitle(R.string.plain_text);
        } else if (mType == Notes.TYPE_TEXT) {
            checklistItem.setTitle(R.string.checklist);
        }
        if (mState == STATE_EDIT) {
            if (Util.isLock(this, getNoteId())) {
                lockItem.setTitle(R.string.unlock);
            } else {
                lockItem.setTitle(R.string.lock);
            }
        }
        if (Util.isRemain(this, getNoteId())) {
            remindItem.setTitle(R.string.unremind);
        }
        // 新建情况下已经设置提醒
        if (remindTime != 0 && (mState == STATE_INSERT)) {
            remindItem.setTitle(R.string.unremind);
        }
        return super.onMenuOpened(featureId, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = 0;
        if (mState == STATE_EDIT) {
            id = Integer.parseInt(mUri.getPathSegments().get(1));
        }
        switch (item.getItemId()) {
            case 1:
                // new note
                newNote();
                return true;
            case 2:
                // share
                saveNote();
                Util.shareNote(this, id, mTitle);
                return true;
            case 3:
                // add to homescreen
                Util.addShortcutToOptions(this, mTitle, id);
                return true;
            case 4:
                // delete
                if (mState == STATE_EDIT) {
                    if (Util.isLock(this, id)) {// 解锁
                        final int idFinal = id;
                        DialogInterface.OnClickListener okInface = new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                Util.getUnlockDialog(NoteEditorActivity.this, idFinal,
                                        deleteLockNoteListener).show();
                            }
                        };
                        String title = getString(R.string.Delete);
                        String message = getString(R.string.delete_one_note_message);
                        Util.getOkCancelDialog(this, title, message, null, okInface).show();

                    } else {

                        final LinkedList<String> ids = new LinkedList<String>();
                        ids.add(String.valueOf(id));
                        final Context context = this;
                        new AlertDialog.Builder(this)
                                .setTitle(getString(R.string.Delete))
                                .setMessage(getString(R.string.delete_one_note_message))
                                .setIcon(android.R.drawable.ic_dialog_info)
                                .setPositiveButton(getString(R.string.alert_dialog_ok),
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                Util.deleteNoteById(context, ids);
                                                finish();
                                            }
                                        })
                                .setNegativeButton(getString(R.string.alert_dialog_cancel), null)
                                .show();
                    }
                }
                return true;
            case 5:
                // checklist
                swichChecklist();
                return true;
            case 6:
                // lock
                if (Util.isLock(this, id)) {// 解锁
                    Util.getUnlockDialog(this, id, lockAndUnlockListener).show();
                } else {// 加锁
                    if (Util.isSettingPasswrd(this)) {
                        ContentValues values = new ContentValues();
                        values.put(NotePad.Notes.LOCK, NotePad.DataValue.IS_LOCK);
                        getContentResolver().update(NotePad.Notes.CONTENT_URI, values,
                                NotePad.Notes._ID + " = " + id, null);
                        lockImage.setVisibility(View.VISIBLE);
                    } else {
                        // 未设置密码时加锁
                        final int noteId = id;
                        new AlertDialog.Builder(this)
                                .setTitle(getString(R.string.set_note_password))
                                .setMessage(getString(R.string.ask_set_note_password))
                                .setIcon(android.R.drawable.ic_dialog_info)
                                .setPositiveButton(getString(R.string.input_ok),
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                Util.getSettingPasswordDialog(
                                                        NoteEditorActivity.this,
                                                        getString(R.string.set_note_password),
                                                        settingPasswordListener, new String[] {
                                                                "lockUnLock", noteId + ""
                                                        }).show();
                                            }
                                        })
                                .setNegativeButton(getString(R.string.input_cancel), null).show();
                    }
                }

                return true;
            case 7: {
                if (Util.isRemain(this, getNoteId())) {
                    if (mState == STATE_INSERT) {
                        id = 0;
                    }
                    Util.cancelAlarmSet(this, id + "");
                    setRemindTime(0);// 取消新建情况下面提醒设置。
                    return true;
                }
                // 新建情况下已经设置提醒
                if (remindTime != 0 && (mState == STATE_INSERT)) {
                    if (mState == STATE_INSERT) {
                        id = 0;
                    }
                    Util.cancelAlarmSet(this, id + "");
                    setRemindTime(0);// 取消新建情况下面提醒设置。
                    return true;
                }
                setRemindTime(0);
                // id 默认值用来判断当前记事本是否已经保存。
                if (mState == STATE_INSERT) {
                    id = 0;
                }
                Util.setNotice(this, id + "", null);
                return true;
            }

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onBackPressed() {
        if (isChanged()) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.save_note)
                    .setMessage(R.string.whether_save_note)
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setPositiveButton(R.string.alert_dialog_ok,
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    boolean success = saveNote();
                                    if (success) {
                                        Intent i = new Intent(NoteEditorActivity.this,
                                                NoteListActivity.class);
                                        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                        startActivity(i);
                                        finish();

                                    }

                                }

                            }).setNegativeButton(R.string.alert_dialog_cancel, null).show();
            return;
        }
        super.onBackPressed();
    }

    private void swichChecklist() {
        if (mType == Notes.TYPE_CHECKLIST) {
            mType = Notes.TYPE_TEXT;
        } else {
            mType = Notes.TYPE_CHECKLIST;
        }
        isTypeChanged = true;
        setNoteContent(mType);
    }

    /**
     * 获取Note内容
     * 
     * @return
     */
    private String getNoteContent() {
        if (mType == Notes.TYPE_TEXT) {
            return mContentView.getText().toString();
        } else if (mType == Notes.TYPE_CHECKLIST) {
            return getChecklistString();
        }
        return null;
    }

    /**
     * 设置Note内容
     * 
     * @param noteType
     */
    private void setNoteContent(int noteType) {
        switch (noteType) {
        // 清单模式
            case Notes.TYPE_CHECKLIST:
                String content = mContentView.getText().toString();
                if (content == null || content.length() == 0) {
                    btnDone.setEnabled(false);
                } else {
                    btnDone.setEnabled(true);
                }
                String[] list = content.split("\n");
                mContentView.setVisibility(View.GONE);
                mChecklistLayout.setVisibility(View.VISIBLE);
                mChecklistLayout.removeAllViews();
                checklistItems.clear();
                for (String s : list) {
                    insertChecklistItem(s, -1);
                }
                break;

            // 文本模式
            case Notes.TYPE_TEXT:
                mChecklistLayout.setVisibility(View.GONE);
                mContentView.setVisibility(View.VISIBLE);
                if (isTypeChanged) {
                    mContentView.setText(getChecklistString());
                }
                break;
        }

    }

    public int getChecklistCount() {
        return checklistItems.size();
    }

    private boolean isChanged() {
        return !noteContent.equals(getNoteContent()) || (mType != origType)
                || !mColor.equals(origColor);
    }

    private String getChecklistString() {
        StringBuilder sb = new StringBuilder();
        String checkflags = getCheckflags();

        for (ChecklistEditText text : checklistItems) {
            if (checkflags.indexOf("1") != -1) {
                if (!TextUtils.isEmpty(text.getText())) {
                    if (text.getCheckflag()) {
                        sb.append("√ ");
                    } else {
                        sb.append("□ ");
                    }
                }
            }
            sb.append(text.getText()).append("\n");
        }

        return sb.toString();
    }

    private String getCheckflags() {
        StringBuilder sb = new StringBuilder();
        for (ChecklistEditText text : checklistItems) {
            if (text.getCheckflag()) {
                sb.append("1");
            } else {
                sb.append("0");
            }
        }
        return sb.toString();
    }

    private void newNote() {
        if (isChanged()) {
            saveNote();
        }
        mUri = Notes.CONTENT_URI;
        Intent i = new Intent(this, NoteEditorActivity.class);
        i.setAction(Intent.ACTION_INSERT);
        i.setData(mUri);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
    }

    private PopupWindow menuPopup;

    Button btnBlue;

    Button btnPink;

    Button btnGreen;

    Button btnOrange;

    Button btnPurple;

    private void showColorSelector() {

        View menuLayout = getLayoutInflater().inflate(R.layout.color_selector, null);
        menuPopup = new PopupWindow(menuLayout, LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);

        menuPopup.setFocusable(true);// 必须，否则无法点击子view
        menuPopup.setOutsideTouchable(true);// 必须，否则点击其它区域无法关闭
        menuPopup.setBackgroundDrawable(new BitmapDrawable());// 同上
        menuPopup.setTouchInterceptor(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getY() < 0) {
                    if (menuPopup.isShowing())
                        menuPopup.dismiss();
                }
                return false;
            }
        });
        btnBlue = (Button) menuLayout.findViewById(R.id.btnBlue);
        btnBlue.setOnClickListener(colorListener);

        btnPink = (Button) menuLayout.findViewById(R.id.btnPink);
        btnPink.setOnClickListener(colorListener);

        btnGreen = (Button) menuLayout.findViewById(R.id.btnGreen);
        btnGreen.setOnClickListener(colorListener);

        btnOrange = (Button) menuLayout.findViewById(R.id.btnOrange);
        btnOrange.setOnClickListener(colorListener);

        btnPurple = (Button) menuLayout.findViewById(R.id.btnPurple);
        btnPurple.setOnClickListener(colorListener);
        switchColor(mColor);
        menuPopup.showAtLocation(findViewById(R.id.note), Gravity.TOP | Gravity.CENTER_HORIZONTAL,
                0, 100);

    }

    private OnClickListener colorListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Button btn = (Button) v;
            String color = btn.getTag().toString();
            switchColor(color);
        }

    };

    /**
     * 切换颜色
     * 
     * @param color
     */
    private void switchColor(String color) {

        if (btnBlue != null) {
            btnBlue.setBackgroundResource(R.drawable.blueblock);
        }
        if (btnPink != null) {
            btnPink.setBackgroundResource(R.drawable.pinkblock);
        }
        if (btnGreen != null) {
            btnGreen.setBackgroundResource(R.drawable.greenblock);
        }
        if (btnOrange != null) {
            btnOrange.setBackgroundResource(R.drawable.orangeblock);
        }
        if (btnPurple != null) {
            btnPurple.setBackgroundResource(R.drawable.purpleblock);
        }
        if (Notes.Color.BLUE.equals(color)) {
            topBar.setBackgroundResource(R.drawable.notetop_blue_bg);
            mContentView.setBackgroundResource(R.drawable.noteblue_bg);
            mChecklistLayout.setBackgroundResource(R.drawable.noteblue_bg);
            if (btnBlue != null) {
                btnBlue.setBackgroundResource(R.drawable.blueblock2);
            }
        } else if (Notes.Color.PINK.equals(color)) {
            topBar.setBackgroundResource(R.drawable.notetop_pink_bg);
            mContentView.setBackgroundResource(R.drawable.notepink_bg);
            mChecklistLayout.setBackgroundResource(R.drawable.notepink_bg);
            if (btnPink != null) {
                btnPink.setBackgroundResource(R.drawable.pinkblock2);
            }
        } else if (Notes.Color.GREEN.equals(color)) {
            topBar.setBackgroundResource(R.drawable.notetop_green_bg);
            mContentView.setBackgroundResource(R.drawable.notegreen_bg);
            mChecklistLayout.setBackgroundResource(R.drawable.notegreen_bg);
            if (btnGreen != null) {
                btnGreen.setBackgroundResource(R.drawable.greenblock2);
            }
        } else if (Notes.Color.ORANGE.equals(color)) {
            topBar.setBackgroundResource(R.drawable.notetop_orange_bg);
            mContentView.setBackgroundResource(R.drawable.noteorange_bg);
            mChecklistLayout.setBackgroundResource(R.drawable.noteorange_bg);
            if (btnOrange != null) {
                btnOrange.setBackgroundResource(R.drawable.orangeblock2);
            }

        } else if (Notes.Color.PURPLE.equals(color)) {
            topBar.setBackgroundResource(R.drawable.notetop_purple_bg);
            mContentView.setBackgroundResource(R.drawable.notepurple_bg);
            mChecklistLayout.setBackgroundResource(R.drawable.notepurple_bg);
            if (btnPurple != null) {
                btnPurple.setBackgroundResource(R.drawable.purpleblock2);
            }
        }
        mColor = color;
    }

    private boolean saveNote() {
        ContentValues values = new ContentValues();
        String text = getNoteContent();
        if (TextUtils.isEmpty(text.trim())) {
            showText(R.string.save_cannot_empty);
            return false;
        }
        boolean isSetRemind = false;
        // 是用来在新建的时候设置提醒
        if (remindTime != 0 && (mState == STATE_INSERT)) {
            values.put(NotePad.Notes.REMIND, NotePad.DataValue.IS_REMIND);
            values.put(NotePad.Notes.REMIND_TIME, String.valueOf(remindTime));
            isSetRemind = true;
        }
        values.put(Notes.COLOR, mColor);
        values.put(Notes.NOTE, text);
        values.put(Notes.TYPE, mType);
        values.put(Notes.TITLE, Util.makeTitle(text));
        int noteId = -1;
        Uri noteUri;
        switch (mState) {
            case STATE_INSERT:
                if (mColor != null) {
                    values.put(Notes.COLOR, mColor);
                }
                noteUri = getContentResolver().insert(mUri, values);
                noteId = Integer.parseInt(noteUri.getPathSegments().get(1));

                if (isSetRemind) {
                    AlarmManager am = (AlarmManager) this.getSystemService(Activity.ALARM_SERVICE);
                    am.set(AlarmManager.RTC_WAKEUP, remindTime, Util.getNoticPin(this, noteId + ""));
                }

                if (isWidgetRequest) {
                    values.clear();
                    values.put(WidgetInfo.WIDGET_ID, mWidgetId);
                    values.put(WidgetInfo.WIDGET_SIZE, mWidgetSize);
                    values.put(WidgetInfo.NOTE_ID, noteId);
                    getContentResolver().insert(WidgetInfo.CONTENT_URI, values);
                    Util.updateWidget(this, noteId);
                }
                break;
            case STATE_EDIT:
                values.put(Notes.MODIFIED_DATE, System.currentTimeMillis());
                getContentResolver().update(mUri, values, null, null);
                noteId = Integer.parseInt(mUri.getPathSegments().get(1));
                break;

        }
        showText(R.string.save_success);
        return true;
    }

    private SettingPasswordInterfaceOkCancelClick settingPasswordListener = new SettingPasswordInterfaceOkCancelClick();

    private LockAndUnlockInterfaceOkCancelClick lockAndUnlockListener = new LockAndUnlockInterfaceOkCancelClick();

    private DeleteLockNoteInterfaceOkCancelClick deleteLockNoteListener = new DeleteLockNoteInterfaceOkCancelClick();

    private class SettingPasswordInterfaceOkCancelClick implements InterfaceOkCancelClick {
        @Override
        public void dealWithOk(boolean isCheckOk, boolean valid, DialogInterface dialog,
                TextView passwordTv, Object tagObject) {

            String[] tagObj = (String[]) tagObject;
            if (tagObject != null) {
                // 设置密码操作
                String tag = passwordTv.getTag().toString();
                String passwordText = passwordTv.getText().toString();

                if ("".equals(passwordText)) {

                    Util.setDialogCanDismiss(dialog, false);
                    dialog.dismiss();
                    showText(R.string.wrong_change_password);
                    return;
                }

                if (isCheckOk) {
                    Util.setDialogCanDismiss(dialog, true);
                    dialog.dismiss();
                    if (tag.equals("insert")) {
                        ContentValues values = new ContentValues();
                        values.put(Settings.PASSWORD, passwordText);
                        getContentResolver().insert(NotePad.Settings.CONTENT_URI, values);
                        Toast.makeText(NoteEditorActivity.this,
                                getString(R.string.new_password_save), Toast.LENGTH_SHORT).show();

                    } else if (tag.equals("update")) {
                        ContentValues values = new ContentValues();
                        values.put(Settings.PASSWORD, passwordText);
                        getContentResolver().update(NotePad.Settings.CONTENT_URI, values, null,
                                null);
                        Toast.makeText(NoteEditorActivity.this,
                                getString(R.string.new_password_save), Toast.LENGTH_SHORT).show();
                    }

                    // 设置密码并加锁
                    if ("lockUnLock".equals(tagObj[0])) {
                        ContentValues values = new ContentValues();
                        values.put(NotePad.Notes.LOCK, NotePad.DataValue.IS_LOCK);
                        getContentResolver().update(NotePad.Notes.CONTENT_URI, values,
                                NotePad.Notes._ID + " = " + tagObj[1], null);
                        lockImage.setVisibility(View.VISIBLE);
                    }
                } else {
                    Util.setDialogCanDismiss(dialog, false);
                    dialog.dismiss();
                    showText(R.string.wrong_change_password);
                }
                return;
            }
        }

        @Override
        public void dealWithCancel(DialogInterface dialog, Object tagObject) {
            Util.setDialogCanDismiss(dialog, true);
            dialog.dismiss();
        }

    }

    private class LockAndUnlockInterfaceOkCancelClick implements InterfaceOkCancelClick {
        @Override
        public void dealWithOk(boolean isCheckOk, boolean valid, DialogInterface dialog,
                TextView passwordTv, Object tagObject) {

            if (isCheckOk) {
                String noteId = passwordTv.getTag().toString();
                Util.setDialogCanDismiss(dialog, true);
                dialog.dismiss();
                ContentValues values = new ContentValues();
                values.put(NotePad.Notes.LOCK, NotePad.DataValue.IS_UNLOCK);
                getContentResolver().update(NotePad.Notes.CONTENT_URI, values,
                        NotePad.Notes._ID + " = " + noteId, null);
                lockImage.setVisibility(View.GONE);

            } else {
                Util.setDialogCanDismiss(dialog, false);
                dialog.dismiss();
            }
        }

        @Override
        public void dealWithCancel(DialogInterface dialog, Object tagObject) {
            Util.setDialogCanDismiss(dialog, true);
            dialog.dismiss();
        }

    }

    private class DeleteLockNoteInterfaceOkCancelClick implements InterfaceOkCancelClick {
        @Override
        public void dealWithOk(boolean isCheckOk, boolean valid, DialogInterface dialog,
                TextView passwordTv, Object tagObject) {

            if (isCheckOk) {
                Util.setDialogCanDismiss(dialog, true);
                dialog.dismiss();
                getContentResolver().delete(mUri, null, null);
                finish();
            } else {
                Util.setDialogCanDismiss(dialog, false);
                dialog.dismiss();
            }
        }

        @Override
        public void dealWithCancel(DialogInterface dialog, Object tagObject) {
            Util.setDialogCanDismiss(dialog, true);
            dialog.dismiss();
        }

    }

    private class unlockCallBack implements InterfaceOkCancelClick {

        @Override
        public void dealWithOk(boolean isCheckOk, boolean valid, DialogInterface dialog,
                TextView passwordTv, Object tagObject) {
            if (isCheckOk) {
                // 解决9个问题，快捷键第一次输错密码，第二次不能进入问题。
                Util.setDialogCanDismiss(dialog, true);
                myDialog = null;
                initNote();
                dialog.dismiss();
            } else {
                // 对话框不能消失。
                Util.setDialogCanDismiss(dialog, false);
                dialog.dismiss();
            }

        }

        @Override
        public void dealWithCancel(DialogInterface dialog, Object tagObject) {
            dialog.dismiss();
            myDialog = null;
            finish();
        }

    }

    private void showText(int StringId) {
        Toast.makeText(this, getString(StringId), Toast.LENGTH_SHORT).show();
    }

    /**
     * 将done键设为可用(供其他类调用)
     */
    public void enableDoneButton() {
        btnDone.setEnabled(true);
    }

    /**
     * 将done键设为不可用(供其他类调用)
     */
    public void disableDoneButton() {
        btnDone.setEnabled(false);
    }

    /**
     * 清单模式相关操作，提供给ChecklistEditText调用
     */

    /**
     * 获取清单项在清单集合中的索引
     * 
     * @param paramView 清单项
     * @return
     */
    public int getChildViewIndex(View paramView) {
        View view = (View) paramView.getParent();
        return this.mChecklistLayout.indexOfChild(view);
    }

    /**
     * 勾选清单项后触发，将当前清单项移到最后
     * 
     * @param paramView
     */
    public void moveChildViewToLast(View paramView) {
        if (checklistItems.getLast() == (ChecklistEditText) paramView) {
            return;
        }
        checklistItems.remove(paramView);
        checklistItems.addLast((ChecklistEditText) paramView);

        View view = (View) paramView.getParent();
        mChecklistLayout.removeView(view);
        mChecklistLayout.addView(view);
    }

    /**
     * 取消清单项的选定后触发，将自己的位置置于已勾选的清单之前。
     * 
     * @param paramView
     */
    public void restoreChildView(View paramView) {
        int index = 0;
        for (int i = 0; i < checklistItems.size(); i++) {
            if (checklistItems.get(i).getCheckflag()) {
                index = i;
                break;
            }
        }
        if (checklistItems.indexOf(paramView) > index) {
            checklistItems.remove(paramView);
            checklistItems.add(index, (ChecklistEditText) paramView);
            View view = (View) paramView.getParent();
            mChecklistLayout.removeView(view);
            mChecklistLayout.addView(view, index);
        }
    }

    /**
     * 删除清单项
     * 
     * @param paramView
     * @return
     */
    public ChecklistEditText removeChildView(View paramView) {
        View view = (View) paramView.getParent();
        int index = getChildViewIndex(paramView);
        this.mChecklistLayout.removeView(view);
        checklistItems.remove(paramView);
        if (index > 0)
            index--;

        return (ChecklistEditText) mChecklistLayout.getChildAt(index).findViewById(R.id.text);

    }

    /**
     * 插入清单项
     * 
     * @param context
     * @param index
     * @return
     */
    public ChecklistEditText insertChecklistItem(String context, int index) {

        View item = this.getLayoutInflater().inflate(R.layout.checklist_item, null);
        ChecklistEditText text = (ChecklistEditText) item.findViewById(R.id.text);
        InputFilter[] filters = {
            new LengthFilter(5000)
        };
        text.setFilters(filters);
        CheckBox cb = (CheckBox) item.findViewById(R.id.check);
        text.setCheckbox(cb);
        if (context.startsWith("√ ")) {
            context = context.substring(2);
            text.setCheckflag(true);
        }
        if (context.startsWith("□ ")) {
            context = context.substring(2);
            text.setCheckflag(false);
        }
        text.setActivity(this);
        text.setText(context);
        if (index != -1) {

            checklistItems.add(index, text);
            mChecklistLayout.addView(item, index);
        } else {
            checklistItems.add(text);
            mChecklistLayout.addView(item);
        }
        return text;
    }

    private long remindTime = 0;

    /**
     * 这个方法主要是用来，在还没有保存记事本的时候设置提醒。
     * 
     * @param setTime
     */
    public void setRemindTime(long setTime) {
        remindTime = setTime;

    }

}
